package com.example.config;

import com.example.service.IDictService;
import com.example.vo.respvo.DictType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据缓存
 * @author wsl
 */
@Component
public class CacheConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IDictService dictService;

    @PostConstruct//Spring初始化后执行
    public void initDictData(){
        this.initDictCache();
    }

    public void initDictCache(){
        List<DictType> dictClassifyKeyValue = dictService.getDictTypeWithOptions();
        final HashMap<String, Object> dictTypeMap = new HashMap<>();
        final Map<String,Object> dictValueMap = new HashMap<>();
        dictClassifyKeyValue.forEach(e->{
            dictTypeMap.put(e.getCode(),e.getOptions());
            StringBuffer typeKey = new StringBuffer();
            typeKey.append("dict_").append(e.getCode());
            redisTemplate.opsForValue().set(typeKey.toString(),e.getOptions());
            e.getOptions().forEach(v->{
                StringBuffer valueKey = new StringBuffer("");
                valueKey.append(e.getCode()).append(":").append(v.getValue());
                dictValueMap.put(valueKey.toString(),v.getLabel());
            });
        });
        redisTemplate.opsForValue().set("sys_dict",dictTypeMap);//字典类型缓存
        redisTemplate.opsForValue().set("sys_dict_value",dictValueMap);//字典值缓存
    }
}
